package com.rsy.crm.workbench.service.Impl;

import com.rsy.crm.util.DateTimeUtil;
import com.rsy.crm.util.SqlSessionUtil;
import com.rsy.crm.util.UUIDUtil;
import com.rsy.crm.vo.PageVo;
import com.rsy.crm.workbench.dao.*;
import com.rsy.crm.workbench.domain.*;
import com.rsy.crm.workbench.service.ClueService;

import java.util.List;
import java.util.Map;

public class ClueServiceImpl implements ClueService {

    //线索
    private ClueDao clueDao = SqlSessionUtil.getSqlSession().getMapper(ClueDao.class);
    private ClueActivityRelationDao clueActivityRelationDao = SqlSessionUtil.getSqlSession().getMapper(ClueActivityRelationDao.class);
    private ClueRemarkDao clueRemarkDao = SqlSessionUtil.getSqlSession().getMapper(ClueRemarkDao.class);

    //客户
    private CustomerDao customerDao = SqlSessionUtil.getSqlSession().getMapper(CustomerDao.class);
    private CustomerRemarkDao customerRemarkDao = SqlSessionUtil.getSqlSession().getMapper(CustomerRemarkDao.class);

    //联系人
    private ContactsDao contactsDao = SqlSessionUtil.getSqlSession().getMapper(ContactsDao.class);
    private ContactsRemarkDao contactsRemarkDao = SqlSessionUtil.getSqlSession().getMapper(ContactsRemarkDao.class);
    private ContactsActivityRelationDao contactsActivityRelationDao = SqlSessionUtil.getSqlSession().getMapper(ContactsActivityRelationDao.class);

    //交易
    private TranDao tranDao = SqlSessionUtil.getSqlSession().getMapper(TranDao.class);
    private TranHistoryDao tranHistoryDao = SqlSessionUtil.getSqlSession().getMapper(TranHistoryDao.class);
    /**
     * 添加线索
     * @param c
     * @return
     */
    @Override
    public boolean save(Clue c) {
        boolean flag = true;

        int count = clueDao.save(c);

        if(count!=1){

            flag = false;

        }

        return flag;
    }

    /**
     * 跳转到线索详细信息页
     * @param id
     * @return
     */
    @Override
    public Clue detail(String id) {

        Clue clue = clueDao.detail(id);


        return clue;
    }

    /**
     * 删除关联
     * @param id
     * @return
     */
    @Override
    public boolean unbund(String id) {
        boolean flag = true;
        int count = clueActivityRelationDao.unbund(id);
        if(count!=1){

            flag = false;

        }
        return flag;
    }

    /**
     * 执行关联市场活动的操作
     * @param cid
     * @param aids
     * @return
     */
    @Override
    public boolean bund(String cid, String[] aids) {
        boolean flag = true;

        for(String aid:aids){

            //取得每一个aid和cid做关联
            ClueActivityRelation car = new ClueActivityRelation();
            car.setId(UUIDUtil.getUUID());
            car.setActivityId(aid);
            car.setClueId(cid);

            //添加关联关系表中的记录
            int count = clueActivityRelationDao.bund(car);
            if(count!=1){
                flag = false;
            }

        }

        return flag;
    }

    /**
     * 线索分页
     * @param map
     * @return
     */
    @Override
    public PageVo<Activity> pageList(Map<String, Object> map) {
       //获取数据
        List<Activity> list = clueDao.getClueListByCondition(map);
        //获取总记录数
        int total = clueDao.getTotalByCondition(map);

        PageVo<Activity> vo = new PageVo<>();
        vo.setList(list);
        vo.setTotal(total);
        return vo;
    }

    /**
     * 线索转换
     * @param clueId 线索id
     * @param tran   交易
     * @param createBy 经办人
     * @return
     */
    @Override
    public boolean convert(String clueId, Tran tran, String createBy) {
        /**
         * 1.获取需要转换的线索
         * 2.提取客户信息不存在添加存在获取 客户对象
         * 3.添加联系人
         * 4.将线索备注转到客户与联系人备注中
         * 5. “线索和市场活动”的关系转换到“联系人和市场活动”的关系
         * 6.如果有创建交易需求，创建一条交易 如果创建了交易，则创建一条该交易下的交易历史(一对多)
         *
         * 7.删除 线索备注 线索和市场活动的关系 线索
         */
        boolean flag = true;
        //创建时间
        String createTime = DateTimeUtil.getSysTime();
        //1.通过id获取线索
        Clue clue = clueDao.getById(clueId);
        //2.通过线索对象提取客户信息，当该客户不存在的时候，新建客户 ->公司（根据公司的名称精确匹配，判断该客户是否存在！）
        String company = clue.getCompany();//获取公司名
        Customer customer = customerDao.getCustomerByName(company);//获取客户
        if (customer == null){

            customer = new Customer();
            customer.setId(UUIDUtil.getUUID());
            customer.setOwner(clue.getOwner());
            customer.setName(company);
            customer.setWebsite(clue.getWebsite());
            customer.setPhone(clue.getPhone());
            customer.setCreateBy(createBy);
            customer.setCreateTime(createTime);
            customer.setContactSummary(clue.getContactSummary());
            customer.setNextContactTime(clue.getNextContactTime());
            customer.setDescription(clue.getDescription());
            customer.setAddress(clue.getAddress());
            //添加客户
            int customerNum = customerDao.save(customer);
            if(customerNum != 1){
                flag = false;
            }

        }


        //3.通过线索对象提取联系人信息，保存联系人
        Contacts contacts = new Contacts();
        contacts.setId(UUIDUtil.getUUID());
        contacts.setSource(clue.getSource());
        contacts.setOwner(clue.getOwner());
        contacts.setNextContactTime(clue.getNextContactTime());
        contacts.setMphone(clue.getMphone());
        contacts.setJob(clue.getJob());
        contacts.setFullname(clue.getFullname());
        contacts.setEmail(clue.getEmail());
        contacts.setDescription(clue.getDescription());
        contacts.setCustomerId(customer.getId());
        contacts.setCreateTime(createTime);
        contacts.setCreateBy(createBy);
        contacts.setContactSummary(clue.getContactSummary());
        contacts.setAppellation(clue.getAppellation());
        contacts.setAddress(clue.getAddress());
        //添加联系人
        int contactsNum = contactsDao.save(contacts);
        if(contactsNum!=1){
            flag = false;
        }

        //(4) 线索备注转换到客户备注以及联系人备注
        //查询出与该线索关联的备注信息列表
        List<ClueRemark> clueRemarkList = clueRemarkDao.getListByClueId(clueId);
        //取出每一条线索的备注
        for(ClueRemark clueRemark : clueRemarkList){

            //取出备注信息（主要转换到客户备注和联系人备注的就是这个备注信息）
            String noteContent = clueRemark.getNoteContent();

            //创建客户备注对象，添加客户备注
            CustomerRemark customerRemark = new CustomerRemark();
            customerRemark.setId(UUIDUtil.getUUID());
            customerRemark.setCreateBy(createBy);
            customerRemark.setCreateTime(createTime);
            customerRemark.setCustomerId(customer.getId());//客户->公司id
            customerRemark.setEditFlag("0");
            customerRemark.setNoteContent(noteContent);

            int count3 = customerRemarkDao.save(customerRemark);
            if(count3!=1){
                flag = false;
            }

            //创建联系人备注对象，添加联系人
            ContactsRemark contactsRemark = new ContactsRemark();
            contactsRemark.setId(UUIDUtil.getUUID());
            contactsRemark.setCreateBy(createBy);
            contactsRemark.setCreateTime(createTime);
            contactsRemark.setContactsId(contacts.getId());//联系人id
            contactsRemark.setEditFlag("0");
            contactsRemark.setNoteContent(noteContent);

            int count4 = contactsRemarkDao.save(contactsRemark);
            if(count4!=1){
                flag = false;
            }

        }
        //(5) “线索和市场活动”的关系转换到“联系人和市场活动”的关系
        //查询出与该条线索关联的市场活动，查询与市场活动的关联关系列表
        List<ClueActivityRelation> clueActivityRelationList = clueActivityRelationDao.getListByClueId(clueId);
        //遍历出每一条与市场活动关联的关联关系记录
        for(ClueActivityRelation clueActivityRelation : clueActivityRelationList){

            //从每一条遍历出来的记录中取出关联的市场活动id
            String activityId = clueActivityRelation.getActivityId();

            //创建 联系人与市场活动的关联关系对象 让第三步生成的联系人与市场活动做关联
            ContactsActivityRelation contactsActivityRelation = new ContactsActivityRelation();
            contactsActivityRelation.setId(UUIDUtil.getUUID());
            contactsActivityRelation.setActivityId(activityId);
            contactsActivityRelation.setContactsId(contacts.getId());
            //添加联系人与市场活动的关联关系
            int count5 = contactsActivityRelationDao.save(contactsActivityRelation);
            if(count5!=1){
                flag = false;
            }


        }

        //6.如果有创建交易需求，创建一条交易
        if(tran!=null){

            /*

                t对象在controller里面已经封装好的信息如下：
                    id,money,name,expectedDate,stage,activityId,createBy,createTime

                接下来可以通过第一步生成的c对象，取出一些信息，继续完善对t对象的封装

             */

            tran.setSource(clue.getSource());//线索来源
            tran.setOwner(clue.getOwner());
            tran.setNextContactTime(clue.getNextContactTime());
            tran.setDescription(clue.getDescription());
            tran.setCustomerId(customer.getId());//客户的id
            tran.setContactSummary(clue.getContactSummary());
            tran.setContactsId(contacts.getId());//联系人id
            //添加交易
            int count6 = tranDao.save(tran);
            if(count6!=1){
                flag = false;
            }

            //7.如果创建了交易，则创建一条该交易下的交易历史
            TranHistory th = new TranHistory();
            th.setId(UUIDUtil.getUUID());
            th.setCreateBy(createBy);
            th.setCreateTime(createTime);
            th.setExpectedDate(tran.getExpectedDate());
            th.setMoney(tran.getMoney());
            th.setStage(tran.getStage());
            th.setTranId(tran.getId());
            //添加交易历史
            int count7 = tranHistoryDao.save(th);
            if(count7!=1){
                flag = false;
            }


        }

        //8.删除线索备注
        for(ClueRemark clueRemark : clueRemarkList){

            int count8 = clueRemarkDao.delete(clueRemark);
            if(count8!=1){
                flag = false;
            }

        }

        //9.删除线索和市场活动的关系
        for(ClueActivityRelation clueActivityRelation : clueActivityRelationList){

            int count9 = clueActivityRelationDao.delete(clueActivityRelation);
            if(count9!=1){

                flag = false;

            }

        }

        //10.删除线索
        int count10 = clueDao.delete(clueId);
        if(count10!=1){
            flag = false;
        }



        return flag;
    }
}
